package com.chang.bootplus.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chang.bootplus.base.annotation.PublicVisit;
import com.chang.bootplus.base.exception.BusException;
import com.chang.bootplus.base.utils.ApiResponse;
import com.chang.bootplus.base.utils.BeanUtil;
import com.chang.bootplus.entity.School;
import com.chang.bootplus.entity.StuExecl;
import com.chang.bootplus.entity.StuTest;
import com.chang.bootplus.entity.Student;
import com.chang.bootplus.mapper.StuTestMapper;
import com.chang.bootplus.mapper.StudentMapper;
import com.chang.bootplus.po.StuAdminDeletePO;
import com.chang.bootplus.po.StuAdminPO;
import com.chang.bootplus.po.StudentInfoPO;
import com.chang.bootplus.po.StudentUpdatePO;
import com.chang.bootplus.service.SchoolService;
import com.chang.bootplus.service.StuExeclService;
import com.chang.bootplus.service.StuTestService;
import com.chang.bootplus.service.StudentService;
import com.chang.bootplus.vo.StudentInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import jodd.io.StreamUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = {"学生管理"})
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RequestMapping("/stuAdmin")
public class StudentAdminController {


    @Autowired
    SchoolService schoolService;



    @Autowired
    StuExeclService stuExeclService;

    @Resource
    StuTestMapper stuTestMapper;

    @Autowired
    StuTestService stuTestService;

    @Autowired
    StudentService studentService;

    @PostMapping("/getBySchool")
    @ApiOperation(httpMethod = "POST",value = "通过学校获取学生信息，无姓名性别为查所有")
    public  ApiResponse<StudentInfoVO> getAllId(@RequestBody StuAdminPO po){
        // sex 为null 其他为空
        String  username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        School one = schoolService.getOne(new LambdaQueryWrapper<School>().eq(School::getNickName, username));

        List<String> gradeList=new LinkedList<>(Arrays.asList(" ","一","二","三","四","五","六"));
        //三年级转化为   3 ;
        String grade=po.getGrade()==null ? null:"1" + gradeList.indexOf(po.getGrade().substring(0,1));
        // 12班转化为  13 10 12
        String className=po.getClassName()==null? null: po.getClassName().substring(0,po.getClassName().length()-1); // 拿到2数字
        if (className!=null){
            if (new Integer(className)<10){// 小于10补前导0
                className="0"+className;
            }
        }
        // 不需要根据时间筛选
//        List<StuExecl> list = stuExeclService.list(new LambdaQueryWrapper<StuExecl>().eq(!(one.getSchoolName().equals("admin")&&po.getSchoolName()==null),StuExecl::getSchoolName, po.getSchoolName()));
//        List<LocalDateTime> collect = list.stream().sorted(Comparator.comparing(StuExecl::getGmtCreate).reversed()).map(StuExecl::getGmtCreate).collect(Collectors.toList());
//        String s1 = collect.get(0).toString();// 排序后拿到最新的时间

        String classId=className==null ? null :"01"+className;
        List<StudentInfoVO> studentInfoVOS=new LinkedList<>();
        List<Student> students=new LinkedList<>();
        int  count = studentService.count(new QueryWrapper<Student>()
                .select("distinct stu_id").lambda()// 根据学号去重
                .like(po.getStuId()!=null,Student::getStuId,po.getStuId())
                .eq(grade!=null,Student::getGradeId,grade)
                .eq(po.getSex()!=null,Student::getSex,po.getSex())
                .like(po.getUsername()!=null,Student::getUsername,po.getUsername())
                .like(classId!=null,Student::getClassId,classId).eq(!(one.getSchoolName().equals("admin")&&po.getSchoolName()==null),Student::getSchoolName,po.getSchoolName()));

        if (!one.getSchoolName().equals("admin")&&!po.getSchoolName().equals(one.getSchoolName())){
            throw new BusException("你没有权限");
        }
        Page<Student> studentPage = new Page<>(po.getPageNumber(),po.getPageSize());

        Page<Student> page = studentService.page(studentPage, new QueryWrapper<Student>()
                .select("distinct stu_id")
                        .lambda()
                        .like(po.getStuId()!=null,Student::getStuId,po.getStuId())// 根据学号去重
                .eq(grade!=null,Student::getGradeId,grade).eq(po.getSex()!=null,Student::getSex,po.getSex())
                .like(po.getUsername()!=null,Student::getUsername,po.getUsername())
                .like(classId!=null,Student::getClassId,classId).eq(!(one.getSchoolName().equals("admin")&&po.getSchoolName()==null),Student::getSchoolName,po.getSchoolName())
                );


        students=BeanUtil.listA2ListB(page.getRecords(),Student.class);

        LinkedList<Student> students1 = new LinkedList<>();
        students.stream().forEach(t->{
            List<Student> collect = studentService.list(new LambdaQueryWrapper<Student>().eq(Student::getStuId, t.getStuId())).stream().sorted(Comparator.comparing(Student::getGmtCreate).reversed()).collect(Collectors.toList());
            Student student1 = collect.get(0);// 拿到最新的学生
            List<Student> list = studentService.list(new LambdaQueryWrapper<Student>().eq(Student::getStuId, student1.getStuId()));
            List<String> collect1 = list.stream().map(t1 -> t1.getOpenId()).collect(Collectors.toList());//获取所有id
            collect1.stream().forEach(t3->{
                if (!t3.equals("0")){
                    student1.setOpenId(t3);//给最新的同学添加上以前同学绑定的情况
                }
            });
            students1.add(student1);
        });


        studentInfoVOS = BeanUtil.listA2ListB(students1, StudentInfoVO.class);
        return new ApiResponse(studentInfoVOS,new Long(students.size()) ,new Long(count));
    }


    @PostMapping("/updateStudent")
    @ApiOperation(httpMethod = "POST",value = "更新学生信息")
    public  ApiResponse<Void> getAll(@RequestBody StudentUpdatePO po){
//        Student one = studentService.getOne(new LambdaQueryWrapper<Student>().eq(Student::getStuId, po.getStuId()));
        Student student = BeanUtil.beanA2beanB(po, Student.class);
        studentService.saveOrUpdate(student);
        return new ApiResponse().setReMsg("更新成功");
    }

    @PostMapping("/addStudent")
    @ApiOperation(httpMethod = "POST",value = "添加学生信息")
    public  ApiResponse<Void> getAll(@RequestBody StuAdminAddPO  po){
        Student one = studentService.getOne(new LambdaQueryWrapper<Student>().eq(Student::getStuId, po.getStuId()));
        if (one!=null){
            throw new BusException("学生已存在");
        }
        Student student = BeanUtil.beanA2beanB(po, Student.class);
        studentService.saveOrUpdate(student);
        return new ApiResponse().setReMsg("添加成功");
    }


    @PostMapping("/deleteStudent")
    @ApiOperation(httpMethod = "POST",value = "删除学生信息")
    public  ApiResponse<Void> deleteStudent(@RequestBody StuAdminDeletePO po){
        List<Student> list = studentService.list(new LambdaQueryWrapper<Student>().eq(Student::getStuId, po.getStuId()));
        if (list.size()==0){
            throw new BusException("学生不存在");
        }
        list.stream().forEach(t->{
            stuTestService.remove(new LambdaQueryWrapper<StuTest>().eq(StuTest::getSchoolName,t.getSchoolName()).eq(StuTest::getStuId,t.getStuId()));
            studentService.removeById(t);
        });

        return new ApiResponse().setReMsg("删除成功");
    }
}
